<template>
  <div>
    <section class="title-bar">
      <el-row>
        <el-col :span="2">
          <el-button type="primary" v-permission="'/api/resources/upload,/api/cos/upload'"
                     @click="addDialogVisible = true" :icon="Plus">新增</el-button>
        </el-col>
        <el-col :span="20">
          <el-form :model="searchData" :inline="true">
            <el-form-item>
              <el-input type="text" placeholder="资源名" v-model="searchData.resourceName" clearable
                        style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-input type="text" placeholder="标签" v-model="searchData.tag" clearable
                        style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="loadTable" type="primary">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="2">
          <el-button type="primary"
                     @click="exportTableVisible = true">导出</el-button>
        </el-col>
      </el-row>
    </section>
    <!-- 表格 -->
    <section>
      <el-table :data="tableData.rows" stripe :border="true" row-key="resourceId" default-expand-all style="width: 100%">
        <el-table-column prop="resourceId" label="系统编号">
        </el-table-column>
        <el-table-column prop="resourceName" label="资源名">
        </el-table-column>
        <el-table-column prop="tag" label="标签">
        </el-table-column>
        <el-table-column prop="resourceDescription" label="资源描述" width="200px">
        </el-table-column>
        <el-table-column prop="userId" label="上传者">
        </el-table-column>
        <el-table-column prop="fa" label="收藏总数">
        </el-table-column>
        <el-table-column prop="liked" label="点赞总数">
        </el-table-column>
        <el-table-column prop="rating" label="平均评分">
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot:default="scope">
            <el-button v-permission="'/api/resources/update,/api/cos/update'" type="primary"
                       :icon="Edit" @click="openUpdateDia(scope.row.resourceId)">编辑
            </el-button>
            <el-button v-permission="'/authority/deleteById,/api/cos/delete'" type="danger" :icon="Delete"
                       @click="deleteById(scope.row.resourceId,scope.row.resourceName)">删除
            </el-button>
            <el-button v-permission="'/api/cos/upload'" type="success" :icon="Plus"
                       @click="goToResourcePage(scope.row.resourceId,scope.row.resourceType)">播放
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>

    <!-- 分页   -->
    <section>
      <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handlePageNowChange"
          :current-page="searchData.pageNow"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="searchData.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
      >
      </el-pagination>
    </section>
    <!-- 新增权限对话框 -->
    <AddAuthority :addDialogVisible="addDialogVisible" @closeDialog="addDialogVisible = false"
                  @addSuccess="handleAddSuccess"></AddAuthority>

    <UpdateAuthority :updateDialogVisible="updateDialogVisible" @closeDialog="updateDialogVisible = false"
                     @updateSuccess="handleUpdateSuccess" :idToUpdate="idToUpdate"></UpdateAuthority>

    <ExportTable :add-dialog-visible="exportTableVisible" @closeDialog="exportTableVisible = false"
                     @updateSuccess="handleExportSuccess"></ExportTable>
  </div>
</template>
<script setup name='AuthorityManage' lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import AddAuthority from '@/views/Resource/AddResource.vue';
import UpdateAuthority from '@/views/Resource/UpdateResource.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {cosApi} from "@/api/resourceApi";
import { resourceApi } from '@/api/resourceApi';
import router from "@/router";
import axios from "axios";
import ExportTable from "@/views/resource/ExportTable.vue";
// 控制新增对话框是否显示
let addDialogVisible = ref(false)
let updateDialogVisible = ref(false)
let exportTableVisible = ref(false)
let idToUpdate = ref('')
let searchData = reactive({
  resourceName: '',
  tag: '',
  pageNow: 1, // 当前页码
  pageSize: 10, // 每页显示的条目数
})
// 表格数据
let tableData = reactive({
  rows: [],
  total: 0, // 总条目数
})

// 打开修改对话框
function openUpdateDia(id: string) {
  idToUpdate.value = id
  updateDialogVisible.value = true
}

// 删除资源
function deleteById(resourceId: string,resourceName: string) {
  ElMessageBox.confirm("确认要删除吗?", "提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cosApi.deleteObject(resourceName)
    resourceApi.getbyId(Number(resourceId)).then(result => {
      if(result.data.coverName){
        cosApi.deleteObject(result.data.coverName)
      }
    })
    resourceApi.deleteResource(Number(resourceId))
        .then(result => {
          ElMessage({ type: "success", message: result.data })
          loadTable()
        })
  })
}


function loadTable() {
  const { tag, resourceName, pageNow, pageSize } = searchData;
  resourceApi.searchResources(tag,resourceName,pageNow,pageSize)
      .then(async result => {
        const res = result.data;
        tableData.total = Number(result.total);
        // 使用 Promise.all 来获取每个资源的收藏总数
        const favoriteCounts = await Promise.all(res.map(resource =>
            axios.get("http://localhost:8000/favorites/count", { params: { resourceId: resource.resourceId } })
        ));
        const favoriteCountslike = await Promise.all(res.map(resource =>
            axios.get("http://localhost:8000/likes/count", { params: { resourceId: resource.resourceId } })
        ));
        const favoriteCountsrating = await Promise.all(res.map(resource =>
            axios.get("http://localhost:8000/ratings/average", { params: { resourceId: resource.resourceId } })
        ));
        // 将每个资源的收藏总数赋值给对应的资源对象
        favoriteCounts.forEach((response, index) => {
          res[index].fa = response.data.data; // 这里假设返回的是总数
        });
        favoriteCountslike.forEach((response, index) => {
          res[index].liked = response.data.data; // 这里假设返回的是总数
        });
        favoriteCountsrating.forEach((response, index) => {
          res[index].rating = response.data; // 这里假设返回的是总数
        });

         tableData.rows = res; // 更新表格数据
      })
}
function handlePageSizeChange(newSize: number) {
  searchData.pageSize = newSize; // 更新每页显示的条目数
  searchData.pageNow = 1; // 重置到第一页
  loadTable(); // 重新加载数据
}

function handlePageNowChange(newPage: number) {
  searchData.pageNow = newPage; // 更新当前页码
  loadTable(); // 重新加载数据
}

function handleAddSuccess() {
  addDialogVisible.value = false
  // 加载表格
  loadTable()
}
// 处理更新成功的事件
function handleUpdateSuccess() {
  updateDialogVisible.value = false
  loadTable()
}
function handleExportSuccess() {
  exportTableVisible.value = false
}
onMounted(() => {
  loadTable()
})

const goToResourcePage = ( resourceId, resourceType) => {
  router.push({ name: 'player', params: {resourceId, resourceType } });
};
function cecece() {
  console.log('测试');
  resourceApi.getbyId(1).then(result => {
    console.log(result);
  });
}
</script>
<style scoped>
.el-tag {
  margin: 3px;
}
</style>